package com.bawei.module_mine.ui

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_mine.R
import com.bawei.module_mine.adapter.SettingAdapter
import com.bawei.module_mine.adapter.TabAdapter
import com.bawei.module_mine.databinding.FragmentMineBinding
import com.bawei.module_mine.model.GetPermissions
import com.bawei.module_mine.model.SettingEntity
import com.google.android.material.tabs.TabLayout.Tab
import com.google.android.material.tabs.TabLayoutMediator
import com.bumptech.glide.Glide
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import com.bawei.module_mine.http.viewModel.LoginViewModel
import com.bawei.module_mine.http.state.LoginState


@Route(path = Router.MINE)
class MineFragment : BaseMVIFragment() {

    private lateinit var binding: FragmentMineBinding
    private lateinit var tabAdapter: TabAdapter
    private var settingAdapter: SettingAdapter? = null
    private lateinit var pickImageLauncher: ActivityResultLauncher<Intent>
    private var avatarUri: String? = null // 可选：用于持久化头像

    // Tab标题
    private val tabTitles = listOf("作品", "动态", "喜欢")

    // 设置项数据
    private val settingData = listOf(
        SettingEntity(R.drawable.ic_order, "我的订单"),
        SettingEntity(R.drawable.ic_wallet, "我的钱包"),
        SettingEntity(R.drawable.ic_function, "历史记录"),
        SettingEntity(R.drawable.ic_qr, "我的二维码"),
        SettingEntity(R.drawable.ic_favorite, "我的收藏"),
        SettingEntity(R.drawable.ic_private, "私密作品"),
        SettingEntity(R.drawable.ic_service, "创作者服务中心"),
        SettingEntity(R.drawable.ic_protect, "未成年保护工具"),
        SettingEntity(R.drawable.ic_setting, "设置")
    )

    // 标记是否已经初始化
    private var isInitialized = false
    private var isViewCreated = false
    private var isSidebarInitialized = false

    private val loginViewModel: LoginViewModel by activityViewModels()

    override fun generateViewModel() {
        // 这里可以初始化ViewModel
    }

    override fun lazyLoad() {
        // 懒加载数据
        initData()
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        binding = FragmentMineBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            loginViewModel.state.collect { state ->
                when (state) {
                    is LoginState.Success -> {
                        val user = state.data
                        Glide.with(this@MineFragment)
                            .load(user?.headImg)
                            .placeholder(R.drawable.ic_person)
                            .circleCrop()
                            .into(binding.ivHeader)
                    }
                    // 其他状态可按需处理
                    is LoginState.AddAccountSuccess -> {}
                    is LoginState.Error -> {}
                    LoginState.Idle -> {}
                    is LoginState.LikeSuccess -> {}
                    LoginState.Loading -> {}
                    is LoginState.MineSuccess -> TODO()
                    else->{}
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isViewCreated = true
        
        // 确保只初始化一次
        if (!isInitialized) {
            initView()
            isInitialized = true
        }
        
        // 初始化监听器
        initListener()
        
        // 确保侧边栏正确初始化
        ensureSidebarInitialized()
        
        // 延迟一下再次确保侧边栏状态正确
        Handler(Looper.getMainLooper()).postDelayed({
            if (isViewCreated && isAdded && !isDetached) {
                ensureSidebarInitialized()
            }
        }, 200)

        // 退出登录按钮点击事件
        val logoutBtn = binding.drawer.findViewById<LinearLayout>(R.id.btn_logout)
        logoutBtn.setOnClickListener {
            // 清除登录信息
            AuthMMKV.token = ""
            AuthMMKV.uId = 0
            AuthMMKV.username = ""
            // 跳转到登录页
            ARouter.getInstance().build(Router.Ui.USER_ACTIVITY).navigation()
        }

        // 注册图片选择回调
        pickImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK && result.data != null) {
                val uri = result.data?.data
                if (uri != null) {
                    // 用Glide加载图片到头像
                    Glide.with(this)
                        .load(uri)
                        .placeholder(R.drawable.ic_person)
                        .circleCrop()
                        .into(binding.ivHeader)
                    // 你可以在这里保存头像uri到本地或上传服务器
                }
            }
        }
    }
    
    override fun onResume() {
        super.onResume()
        if (isViewCreated) {
            // 确保侧边栏状态正确
            ensureSidebarInitialized()
        }
    }
    
    override fun onPause() {
        super.onPause()
        // 在onPause中关闭侧边栏
        if (::binding.isInitialized) {
            closeDrawer()
        }
    }
    
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden && isViewCreated) {
            // Fragment变为可见时，确保侧边栏正确初始化
            Handler(Looper.getMainLooper()).postDelayed({
                ensureSidebarInitialized()
            }, 50) // 减少延迟时间
        } else if (hidden) {
            // Fragment隐藏时，关闭侧边栏
            if (::binding.isInitialized) {
                closeDrawer()
            }
        }
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        isViewCreated = false
        isSidebarInitialized = false
        // 清理资源
        if (::binding.isInitialized) {
            try {
                binding.dl.removeDrawerListener(drawerListener)
            } catch (e: Exception) {
                Log.e("MineFragment", "移除DrawerLayout监听器失败", e)
            }
        }
        // 清理TabAdapter的Fragment缓存
        if (::tabAdapter.isInitialized) {
            tabAdapter.clearFragments()
        }
    }
    
    // 处理ViewPager2中的Fragment可见性变化
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        Log.d("MineFragment", "setUserVisibleHint: $isVisibleToUser")
        
        if (isVisibleToUser && isViewCreated) {
            // Fragment变为可见时，确保侧边栏正确初始化
            Handler(Looper.getMainLooper()).postDelayed({
                ensureSidebarInitialized()
            }, 50) // 减少延迟时间
        } else if (!isVisibleToUser) {
            // Fragment变为不可见时，关闭侧边栏
            if (::binding.isInitialized) {
                closeDrawer()
            }
        }
    }
    
    private fun ensureSidebarInitialized() {
        if (::binding.isInitialized && isAdded && !isDetached && isViewCreated) {
            try {
                Log.d("MineFragment", "开始确保侧边栏初始化")
                
                // 确保DrawerLayout处于正确状态
                binding.dl.closeDrawer(GravityCompat.END)
                
                // 确保侧边栏适配器正确初始化
                if (!isSidebarInitialized || binding.rvMine.adapter == null) {
                    Log.d("MineFragment", "需要初始化侧边栏适配器")
                    initSidebarAdapter()
                    isSidebarInitialized = true
                } else {
                    Log.d("MineFragment", "侧边栏适配器已存在，刷新数据")
                    settingAdapter?.notifyDataSetChanged()
                }
                
                // 设置DrawerLayout监听器
                setupDrawerListener()
                
                // 确保设置按钮可以点击
                binding.setting.isClickable = true
                binding.setting.isEnabled = true
                
                // 确保RecyclerView可见
                binding.rvMine.visibility = View.VISIBLE
                binding.drawer.visibility = View.VISIBLE
                
                Log.d("MineFragment", "侧边栏初始化完成")
            } catch (e: Exception) {
                Log.e("MineFragment", "侧边栏初始化失败", e)
                // 如果初始化失败，重置状态
                isSidebarInitialized = false
                settingAdapter = null
            }
        } else {
            Log.w("MineFragment", "无法初始化侧边栏: binding=${::binding.isInitialized}, isAdded=$isAdded, isDetached=$isDetached, isViewCreated=$isViewCreated")
        }
    }

    override fun initView() {
        // 初始化TabLayout和ViewPager2
        tabAdapter = TabAdapter(requireActivity())
        binding.vp.adapter = tabAdapter
        
        // 设置TabLayout和ViewPager2联动
        TabLayoutMediator(binding.tab, binding.vp) { tab, position ->
            tab.text = tabTitles[position]
        }.attach()
        
        // 初始化侧边栏RecyclerView的布局管理器
        binding.rvMine.layoutManager = LinearLayoutManager(requireContext())
        
        Log.d("MineFragment", "initView完成")

        val phone = AuthMMKV.username
        if (!phone.isNullOrEmpty()){
            binding.tvName.setText(GetPermissions.desensitizePhoneNumber(phone))
        }

        // 可选：进入页面时自动加载本地保存的头像
        avatarUri?.let {
            Glide.with(this)
                .load(it)
                .placeholder(R.drawable.ic_person)
                .circleCrop()
                .into(binding.ivHeader)
        }
    }

    private fun initListener() {
        // 设置按钮点击事件 - 打开侧边栏
        binding.setting.setOnClickListener {
            Log.d("MineFragment", "设置按钮被点击")
            openDrawer()
        }

        // 添加调试按钮（可选）
        binding.tvName.setOnClickListener {
            Log.d("MineFragment", "用户名被点击，检查DrawerLayout状态")
            checkDrawerLayoutState()
        }

        // TabLayout选择监听
        binding.tab.addOnTabSelectedListener(object : com.google.android.material.tabs.TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: Tab?) {
                tab?.let {
                    val tabName = tabTitles[it.position]
                    Log.d("MineFragment", "选中了Tab: $tabName")
                    
                    // 根据选中的Tab执行不同的操作
                    when(it.position) {
                        0 -> {
                            // 作品页面
                            handleWorksTab()
                        }
                        1 -> {
                            // 动态页面
                            handleDynamicTab()
                        }
                        2 -> {
                            // 喜欢页面
                            handleLikeTab()
                        }
                    }
                }
            }

            override fun onTabUnselected(tab: Tab?) {
                // Tab取消选中
            }

            override fun onTabReselected(tab: Tab?) {
                // Tab重新选中
                tab?.let {
                    val tabName = tabTitles[it.position]
                    Log.d("MineFragment", "重新点击：$tabName")
                }
            }
        })
        binding.tvName.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.USER_ACTIVITY).navigation()
        }
        // 用户信息区域点击事件
        binding.ivHeader.setOnClickListener {
            // 打开系统图片选择器
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            pickImageLauncher.launch(intent)
        }
    }

    private fun initSidebarAdapter() {
        try {
            Log.d("MineFragment", "开始初始化侧边栏适配器")
            
            // 确保RecyclerView可见
            binding.rvMine.visibility = View.VISIBLE
            binding.drawer.visibility = View.VISIBLE
            
            // 创建新适配器
            settingAdapter = SettingAdapter(settingData)
            binding.rvMine.adapter = settingAdapter
            
            Log.d("MineFragment", "适配器创建完成，数据项数量: ${settingData.size}")
            
            // 设置侧边栏点击监听
            settingAdapter?.setOnItemClickListener { position ->
                Log.d("MineFragment", "侧边栏项目被点击: position=$position")
                when(position) {
                    0 -> {
                        // 我的订单
                        ARouter.getInstance().build("/mine/OrderActivity").navigation()
                    }
                    1 -> {
                        // 我的钱包 - 跳转到金币页面
                        ARouter.getInstance().build(Router.Ui.GOLD_ACTIVITY).navigation()
                    }
                    2 -> {
                        // 功能
                        ARouter.getInstance().build("/mine/HistoryActivity").navigation()
                    }
                    3 -> {
                        // 我的二维码
                        ARouter.getInstance().build("/mine/DimensionalActivity").navigation()
                    }
                    4 -> {
                        ARouter.getInstance().build("/mine/CollectActivity").navigation()
                    }
                    5 -> {
                        // 私密作品
                        ARouter.getInstance().build(Router.Ui.SHOP_DETAIL_ACTIVITY).navigation()
                    }
                    6 -> {
                        // 创作者服务中心
                        Toast.makeText(requireContext(), "点击了：创作者服务中心", Toast.LENGTH_SHORT).show()
                        Log.d("MineFragment", "点击了：创作者服务中心")
                    }
                    7 -> {
                        // 未成年保护工具
                        ARouter.getInstance().build("/mine/ChildManagerActivity").navigation()
                        Log.d("MineFragment", "点击了：未成年保护工具")
                    }
                    8 -> {
                        // 设置
                        Toast.makeText(requireContext(), "点击了：设置", Toast.LENGTH_SHORT).show()
                        Log.d("MineFragment", "点击了：设置")
                    }
                }
                // 关闭侧边栏
                closeDrawer()
            }
            
            // 强制刷新适配器
            settingAdapter?.notifyDataSetChanged()
            
            Log.d("MineFragment", "侧边栏适配器初始化完成")
            
        } catch (e: Exception) {
            Log.e("MineFragment", "初始化侧边栏适配器失败", e)
            // 重置适配器
            settingAdapter = null
            binding.rvMine.adapter = null
        }
    }

    private fun checkDrawerLayoutState() {
        if (::binding.isInitialized) {
            Log.d("MineFragment", "=== DrawerLayout状态检查 ===")
            Log.d("MineFragment", "Fragment状态: isAdded=$isAdded, isDetached=$isDetached, isVisible=$isVisible, isViewCreated=$isViewCreated")
            Log.d("MineFragment", "设置按钮状态: clickable=${binding.setting.isClickable}, enabled=${binding.setting.isEnabled}")
            Log.d("MineFragment", "DrawerLayout状态: isDrawerOpen=${binding.dl.isDrawerOpen(GravityCompat.END)}")
            Log.d("MineFragment", "侧边栏初始化状态: $isSidebarInitialized")
            
            // 检查RecyclerView状态
            Log.d("MineFragment", "RecyclerView适配器: ${binding.rvMine.adapter}")
            Log.d("MineFragment", "RecyclerView子视图数量: ${binding.rvMine.childCount}")
            
            // 尝试手动打开侧边栏
            Log.d("MineFragment", "尝试手动打开侧边栏...")
            openDrawer()
            
            Log.d("MineFragment", "=== 状态检查结束 ===")
        } else {
            Log.w("MineFragment", "Binding未初始化，无法检查状态")
        }
    }

    private fun setupDrawerListener() {
        if (::binding.isInitialized) {
            try {
                // 移除之前的监听器，避免重复添加
                binding.dl.removeDrawerListener(drawerListener)
                // 添加新的监听器
                binding.dl.addDrawerListener(drawerListener)
                Log.d("MineFragment", "DrawerLayout监听器设置成功")
            } catch (e: Exception) {
                Log.e("MineFragment", "设置DrawerLayout监听器失败", e)
            }
        }
    }

    // 创建DrawerLayout监听器对象，避免重复创建
    private val drawerListener = object : DrawerLayout.DrawerListener {
        override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
            // 滑动中
        }

        override fun onDrawerOpened(drawerView: View) {
            // 侧边栏打开
            Log.d("MineFragment", "侧边栏已打开")
            // 确保数据正确显示
            settingAdapter?.notifyDataSetChanged()
        }

        override fun onDrawerClosed(drawerView: View) {
            // 侧边栏关闭
            Log.d("MineFragment", "侧边栏已关闭")
        }

        override fun onDrawerStateChanged(newState: Int) {
            // 状态改变
            Log.d("MineFragment", "DrawerLayout状态改变: $newState")
        }
    }

    private fun openDrawer() {
        if (::binding.isInitialized && isAdded && !isDetached && isViewCreated) {
            try {
                Log.d("MineFragment", "尝试打开侧边栏")
                
                // 检查DrawerLayout状态
                if (binding.dl.isDrawerOpen(GravityCompat.END)) {
                    Log.d("MineFragment", "侧边栏已经打开")
                    return
                }
                
                // 确保侧边栏适配器正确初始化
                if (!isSidebarInitialized || binding.rvMine.adapter == null) {
                    initSidebarAdapter()
                    isSidebarInitialized = true
                }
                
                binding.dl.openDrawer(GravityCompat.END)
                
                // 验证是否成功打开
                Handler(Looper.getMainLooper()).postDelayed({
                    if (binding.dl.isDrawerOpen(GravityCompat.END)) {
                        Log.d("MineFragment", "侧边栏打开成功")
                        // 确保数据正确显示
                        settingAdapter?.notifyDataSetChanged()
                    } else {
                        Log.w("MineFragment", "侧边栏打开失败，尝试重新打开")
                        try {
                            binding.dl.openDrawer(GravityCompat.END)
                        } catch (e: Exception) {
                            Log.e("MineFragment", "重新打开侧边栏失败", e)
                        }
                    }
                }, 50) // 减少延迟时间
                
            } catch (e: Exception) {
                Log.e("MineFragment", "打开侧边栏失败", e)
                // 如果打开失败，尝试重置状态后再次打开
                try {
                    binding.dl.closeDrawer(GravityCompat.END)
                    Handler(Looper.getMainLooper()).postDelayed({
                        if (::binding.isInitialized && isAdded && !isDetached && isViewCreated) {
                            try {
                                binding.dl.openDrawer(GravityCompat.END)
                            } catch (e2: Exception) {
                                Log.e("MineFragment", "延迟打开侧边栏失败", e2)
                            }
                        }
                    }, 100) // 减少延迟时间
                } catch (e2: Exception) {
                    Log.e("MineFragment", "重置DrawerLayout状态失败", e2)
                }
            }
        } else {
            Log.w("MineFragment", "无法打开侧边栏: binding=${::binding.isInitialized}, isAdded=$isAdded, isDetached=$isDetached, isViewCreated=$isViewCreated")
        }
    }

    private fun closeDrawer() {
        if (::binding.isInitialized && isAdded && !isDetached) {
            try {
                binding.dl.closeDrawer(GravityCompat.END)
            } catch (e: Exception) {
                Log.e("MineFragment", "关闭侧边栏失败", e)
            }
        }
    }

    private fun handleWorksTab() {
        // 处理作品Tab的逻辑
        Log.d("MineFragment", "处理作品Tab")
    }

    private fun handleDynamicTab() {
        // 处理动态Tab的逻辑
        Log.d("MineFragment", "处理动态Tab")
    }

    private fun handleLikeTab() {
        // 处理喜欢Tab的逻辑
        Log.d("MineFragment", "处理喜欢Tab")
    }

    override fun initData() {
        // 初始化数据
        Log.d("MineFragment", "初始化数据")
    }
}